from .id_generator import generate_unique_id

def display_items(items):
    """
    Display all items nicely.
    
    Arg:        
    items (list): A list of dictionaries, where each dictionary represents an item.
    """
    if not items:
        print("No items in collection.")
    else:
        return items
    
def create_item(items, name, item_type, age, image_path=None):
    """
    Create a new item with unique ID and save it.

    Arg:
    items (list): A list of dictionaries where each dictionary represents an existing item.
    name (str): The name of the new item (cannot be empty).
    item_type (str): The type of the new item (cannot be empty).
    age (int): The age of the new item.
    image_path (str, optional): The path to the item's image.

    Returns:
    tuple: A tuple where the first element is a boolean (True if creation is successful, False otherwise),
           and the second element is a message indicating the result.
    """
    ALLOWED_TYPES = ["Warrior","Assassin","Mage","Marksman","Support"]
    if len(items) >= 4:
        return False, "Error: Maximum 4 items allowed!"
    if not name or not item_type:
        return False, "Error: Name and item_type cannot be empty!"
    if item_type.strip() not in ALLOWED_TYPES:
        return False, "must using the 5 types"
    new_item = {
        "id": generate_unique_id(items),
        "name": name.strip(),
        "item_type": item_type.strip(),
        "age": age
    }
    if image_path:
        new_item["image_path"] = image_path
    items.append(new_item)
    return True, f"Item '{name}' created successfully (ID: {new_item['id']})"

def delete_item(items, item_id):
    """
    Delete an item from the list by its ID.
    
    Arg:
        items (list): A list of dictionaries, where each dictionary represents an item.
        item_id (str | int): The unique ID of the item to be delete.
    """
    for idx, item in enumerate(items):
        if item['id'] == item_id:
            deleted_item = items.pop(idx)
            print(f"You successfully deleted {deleted_item}.")
            return True, f"Item with ID {item_id} deleted successfully!"
    return False, f"Error: Item with ID {item_id} not found!"

def edit_item(items, item_id, new_name, new_item_type, new_age, new_image_path=None):
    """
    Edit an existing item's details by ID.

    Args:
        items (list): A list of dictionaries, each representing an item (must contain "id", "name", "item_type", "age" keys).
        item_id (str/int): The unique ID of the item to be edited.
        new_name (str): The new name for the item (cannot be empty).
        new_item_type (str): The new type for the item (cannot be empty).
        new_age (str/int): The new age for the item.
        new_image_path (str, optional): The new image path for the item.

    Returns:
        tuple: A tuple where the first element is a boolean (True if edit is successful, False otherwise),
               and the second element is a message indicating the result (success message with updated info or error message).
    """
    if not new_name or not new_item_type:
        return False, "Error: Name and item_type cannot be empty!"
    
    try:
        item_id = int(item_id)
    except (ValueError, TypeError):
        pass
    
    for item in items:
        if item["id"] == item_id:
            item["name"] = new_name.strip()
            item["item_type"] = new_item_type.strip()
            try:
                item["age"] = new_age.strip()
            except AttributeError:
                item["age"] = new_age
        
        if new_image_path is not None:
            if new_image_path:
                item["image_path"] = new_image_path
            elif "image_path" in item:
                del item["image_path"]
                
        return True, f"Item with ID {item_id} updated successfully!"
    return False, f"Error: Item with ID {item_id} not found!"

def search_items(items, keyword):
    """
    Search for items by keyword, supporting fuzzy matching in name, category, and description (case-insensitive).

    Args:
        items (list): A list of item dictionaries, each must contain "name", "category", and "description" keys.
        keyword (str): The search keyword, which will be processed to lowercase and stripped of leading/trailing spaces.

    Returns:
        list: A list of item dictionaries that match the keyword; returns an empty list if no matches are found.
    """
    keyword = keyword.lower().strip()
    return [
        item for item in items
        if keyword in item["name"].lower() 
        or keyword in item["item_type"].lower()
        or keyword in str(item["age"])
    ]

if __name__ == "__main__":
    pass

